package com.hl.icd.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.hl.icd.bean.ICD;
import com.hl.icd.bean.ResultVo;
import com.hl.icd.bean.User;
import com.hl.icd.exception.ICDException;
import com.hl.icd.service.UserService;
import com.hl.icd.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.http.HttpHeaders;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@CrossOrigin
@RequestMapping(value = "/user")
@Api(tags="用户管理接口文档")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    @PostMapping(value = "/login")
    @ResponseBody
    @ApiOperation(
            value = "登录功能",
            notes = "根据用户提供的用户名和密码进行登录验证，并携带验证成功的用户信息和有效token返回",
            httpMethod = "POST",
            response = User.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "user",value = "用户登录所携带的信息", required = true),
            @ApiImplicitParam(name = "session",value = "会话作用域对象，浏览器自动发送")
    })
    public User login(@RequestBody User user, HttpSession session){
        try {
            user = userService.login(user);
            String jws = jwtUtil.createJWS("login-token",user);
            user.setToken(jws);
            session.setAttribute("user",user);
        } catch (ICDException e){
            user.setMessage(e.getMessage());
        }
        return user;
    }

    @PostMapping(value = "/signUp")
    @ResponseBody
    @ApiOperation(
            value = "注册功能",
            notes = "根据用户提供的注册信息进行用户注册操作",
            httpMethod = "POST",
            response = ResultVo.class)
    @ApiImplicitParam(name = "user",value = "用户注册所携带的信息", required = true)
    public ResultVo signUp(@RequestBody User user){
        ResultVo vo = new ResultVo();
        try {
            userService.signUp(user,"user");
            vo.setOK(true);
        }catch (ICDException e){
            vo.setMessage(e.getMessage());
        }
        return vo;
    }

    @GetMapping(value = "/checkToken")
    @ResponseBody
    @ApiOperation(
            value = "验证token",
            notes = "当有人非法调用接口时进行token验证，如果验证不通过将无法获取数据",
            httpMethod = "GET",
            response = Boolean.class)
    @ApiImplicitParam(name = "request",value = "请求作用域对象，浏览器自动发送")
    public boolean checkToken(HttpServletRequest request){
        String token = request.getHeader("token");
        if(token == null){
            return false;
        }
        try {
            jwtUtil.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @GetMapping(value = "/userQuery/{pageNum}/{pageSize}",produces="text/html;charset=UTF-8")
    @ResponseBody
    @ApiOperation(
            value = "获取用户列表",
            notes = "根据页数和每页的数量分页获取用户列表",
            httpMethod = "GET",
            response = String.class)
    public String userQuery(@PathVariable("pageNum") int pageNum,
                            @PathVariable("pageSize") int pageSize,
                            User user){
        String json = "";
        ObjectMapper om = new ObjectMapper();
        List<User> users = userService.userQuery(pageNum,pageSize,user);
        Map<String,Object> resMap = new HashMap<>();
        PageInfo pageInfo = new PageInfo(users);
        String total = String.valueOf(pageInfo.getTotal());
        resMap.put("total",total);
        resMap.put("data",users);
        try {
            json = om.writeValueAsString(resMap);
            System.out.println(json);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return json;
    }

    @ApiOperation(
            value = "添加用户信息功能",
            notes = "根据前端提供的用户信息进行用户添加操作，此方法一般用在管理员对用户表的操作",
            httpMethod = "POST",
            response = String.class)
    @ApiImplicitParam(name = "user",value = "用户添加所携带的信息", required = true)
    @PostMapping(value = "/userSave",produces="text/html;charset=UTF-8")
    @ResponseBody
    public String userSave(@RequestBody User user){
        return userService.insertOne(user);
    }

    @ApiOperation(
            value = "更新用户信息功能",
            notes = "根据前端提供的用户信息进行用户更新操作，此方法一般用在管理员对用户表的操作",
            httpMethod = "PUT",
            response = String.class)
    @ApiImplicitParam(name = "user",value = "用户添加所携带的信息", required = true)
    @PutMapping(value = "/userUpdate",produces="text/html;charset=UTF-8")
    @ResponseBody
    public String userUpdate(@RequestBody User user){
        return userService.updateOne(user);
    }

    @ApiOperation(
            value = "删除用户功能",
            notes = "根据前端提供的用户信息进行用户删除操作，此方法一般用在管理员对用户表的操作",
            httpMethod = "DELETE",
            response = String.class)
    @ApiImplicitParam(name = "id",value = "所删除的用户的id", required = true)
    @DeleteMapping(value = "/deleteOne/{id}",produces="text/html;charset=UTF-8")
    @ResponseBody
    public String deleteOne(@PathVariable String id){
        return userService.deleteOneById(id);
    }

    @ApiOperation(
            value = "批量删除用户功能",
            notes = "根据前端提供的用户信息进行用户批量删除操作，此方法一般用在管理员对用户表的操作",
            httpMethod = "DELETE",
            response = String.class)
    @ApiImplicitParam(name = "ids",value = "所删除的用户的id的list集合", required = true)
    @DeleteMapping(value = "/deleteBatch",produces="text/html;charset=UTF-8")
    @ResponseBody
    public String deleteBatch(@RequestBody List<String> ids){
        return userService.deleteBatch(ids);
    }

    @PutMapping(value = "/updateState/{id}/{state}",produces="text/html;charset=UTF-8")
    @ResponseBody
    public String updateState(@PathVariable String id,
                            @PathVariable String state){
        return userService.updateState(id,state);
    }
}
